// 页面上下文拦截脚本
(function() {
  console.log('🎯 页面上下文拦截器已注入');
  
  // 默认拦截规则
  let interceptionRules = [
    {
      id: 'rule_1',
      name: '🏦 杭州银行流水',
      urlPattern: '/uc-server/service/hzDealDetailReport/hzDealDetailQuery',
      method: '',
      matchType: 'includes',
      enabled: true
    },
    {
      id: 'rule_2',
      name: '📦 政采云订单',
      urlPattern: '/api/mall/order/list',
      method: 'POST',
      matchType: 'exact',
      enabled: true
    },
    {
      id: 'rule_3',
      name: '📢 政采云公告',
      urlPattern: '/announcement/lobby/queryPage',
      method: '',
      matchType: 'includes',
      enabled: true
    }
  ];
  
  // 监听来自content script的消息
  window.addEventListener('message', function(event) {
    // 确保消息来源是同一个页面
    if (event.source !== window) return;
    
    // 处理规则更新消息
    if (event.data && event.data.type === 'LX_PLUGIN_RULES_UPDATE') {
      console.log('📥 接收到规则更新消息:', event.data.rules);
      
      // 更新拦截规则
      if (event.data.rules && Array.isArray(event.data.rules)) {
        // 直接使用接收到的规则，包括启用状态
        interceptionRules = event.data.rules.map(rule => ({
          urlPattern: rule.urlPattern,
          method: rule.method || '',  // 添加method字段，空值表示拦截所有方法
          matchType: rule.matchType || 'includes',  // 添加matchType字段
          dataType: rule.dataType || 'other',  // 添加数据类型字段
          enabled: rule.enabled !== false,  // 添加启用状态
          captureHtml: rule.captureHtml || false,  // 添加捕获HTML字段
          extractShopId: rule.extractShopId || false,  // 添加提取ShopId字段
          targetShopIds: Array.isArray(rule.targetShopIds) ? rule.targetShopIds : 
                      (rule.targetShopIds && typeof rule.targetShopIds === 'object' ? 
                       Object.values(rule.targetShopIds) : 
                       [])  // 添加目标ShopId列表字段，确保是数组格式
        }));
        console.log('🔧 已更新页面拦截规则:', interceptionRules.length, '条');
        // 详细输出每条规则
        console.log('📋 当前页面拦截规则详情:');
        interceptionRules.forEach((rule, index) => {
          console.log(`  ${index + 1}. URL模式: ${rule.urlPattern}`);
          console.log(`     - 匹配类型: ${rule.matchType || 'includes'}`);
          console.log(`     - HTTP方法: ${rule.method || 'ALL'}`);
          console.log(`     - 数据类型: ${rule.dataType || 'other'}`);
          console.log(`     - 启用状态: ${rule.enabled ? '启用' : '禁用'}`);
          console.log(`     - 提取ShopId: ${rule.extractShopId ? '启用' : '禁用'}`);
          console.log(`     - 目标ShopId: ${rule.targetShopIds && rule.targetShopIds.length > 0 ? rule.targetShopIds.join(', ') : '所有'}`);
        });
      }
    }
  });

  // 添加一个函数来手动检查当前的拦截规则
  function checkCurrentRules() {
    console.log('🔍 手动检查当前拦截规则:', interceptionRules);
    return interceptionRules;
  }
  
  // 添加一个全局函数，方便在控制台中调用
  window.checkLxPluginRules = checkCurrentRules;

  // 拦截 Fetch
  const originalFetch = window.fetch;
  window.fetch = async function(...args) {
    const url = args[0];
    const options = args[1] || {};
    
    try {
      // 特殊处理：捕获请求体中的shopId（仅当规则要求时）
      let shopIds = [];
      let shouldExtractShopId = false;
      let matchedRuleForShopId = null;
      
      // 检查是否有启用extractShopId的规则匹配当前请求
      for (const rule of interceptionRules) {
        if (rule.enabled !== false && rule.extractShopId && 
            isUrlMatch(url, rule.urlPattern, rule.matchType) && 
            (!rule.method || rule.method === (options.method || 'GET'))) {
          shouldExtractShopId = true;
          matchedRuleForShopId = rule;
          break;
        }
      }
      
      if (shouldExtractShopId && options.body && typeof options.body === 'string') {
        try {
          const requestBody = JSON.parse(options.body);
          if (requestBody.shopId) {
            shopIds.push(requestBody.shopId.toString()); // 确保是字符串格式
          }
          // 如果有shopIds数组字段
          if (requestBody.shopIds && Array.isArray(requestBody.shopIds)) {
            shopIds = shopIds.concat(requestBody.shopIds.map(id => id.toString())); // 确保是字符串格式
          }
        } catch (e) {
          // 如果不是有效的JSON，忽略错误
        }
      }
      
      const response = await originalFetch.apply(this, args);
      const urlString = typeof url === 'string' ? url : url.toString();
      const method = options.method || 'GET';
      
      // 检查是否匹配拦截规则
      let isMatched = false;
      let matchedRule = null;
      for (const rule of interceptionRules) {
        // 检查规则是否启用，URL和方法是否匹配
        if (rule.enabled !== false && 
            isUrlMatch(urlString, rule.urlPattern, rule.matchType) && 
            (!rule.method || rule.method === method)) {
          isMatched = true;
          matchedRule = rule;
          break;
        }
      }
      
      // 只有匹配到拦截规则时才输出日志和发送数据
      if (isMatched) {
        console.log('🔍 Fetch请求:', urlString, 'Method:', method);
        console.log('✅ Fetch匹配到规则:', matchedRule.urlPattern, 'Method:', matchedRule.method || 'ALL', 'MatchType:', matchedRule.matchType || 'includes');
        console.log('✅ [页面拦截] Fetch匹配到目标URL:', urlString);
        
        const clonedResponse = response.clone();
        const responseText = await clonedResponse.text();
        let responseData;
        try {
          responseData = JSON.parse(responseText);
        } catch (e) {
          responseData = responseText;
        }
      
        console.log('📦 [页面拦截] Fetch响应数据:', responseData);
    
        // 构造发送到content script的数据
        const messageData = {
          url: urlString,
          fullUrl: urlString.startsWith('http') ? urlString : window.location.origin + urlString,
          method: method,
          timestamp: new Date().toISOString(),
          response: responseData, // 发送完整的响应数据
          status: response.status,
          captureHtml: matchedRule.captureHtml,  // 添加捕获HTML标志
          shopIds: shopIds.length > 0 ? shopIds : undefined  // 添加shopIds
        };

        // 特殊处理：如果需要提取ShopId并且匹配了目标ShopId，则发送完整数据但标记需要提取ShopId
        if (shouldExtractShopId && shopIds.length > 0 && matchedRuleForShopId) {
          // 确保targetShopIds是数组格式
          const targetShopIdsArray = Array.isArray(matchedRuleForShopId.targetShopIds) ? 
                                matchedRuleForShopId.targetShopIds : 
                                (matchedRuleForShopId.targetShopIds && typeof matchedRuleForShopId.targetShopIds === 'object' ? 
                                 Object.values(matchedRuleForShopId.targetShopIds) : 
                                 []);
        
          // 检查是否匹配目标ShopId
          let shopIdMatched = false;
          if (!targetShopIdsArray || targetShopIdsArray.length === 0) {
            // 如果没有指定目标ShopId，则匹配所有
            shopIdMatched = true;
          } else {
            // 检查是否有任何一个shopId在目标列表中
            for (const shopId of shopIds) {
              if (targetShopIdsArray.includes(shopId)) {
                shopIdMatched = true;
                break;
              }
            }
          }
        
          if (shopIdMatched) {
            console.log('✅ [页面拦截] ShopId匹配成功:', shopIds.join(', '));
            // 发送完整数据，但标记需要提取ShopId
            messageData.extractShopId = true;
          } else {
            console.log('ℹ️ [页面拦截] ShopId不匹配目标列表:', shopIds.join(', '), '目标列表:', targetShopIdsArray.join(', '));
            // 如果ShopId不匹配，则不发送数据
            return;
          }
        }
      
        // 发送自定义事件到 content script
        window.postMessage({
          type: 'INTERCEPTED_REQUEST',
          data: messageData
        }, '*');
      }
      
      return response;
    } catch (error) {
      // 只有匹配到拦截规则时才输出错误日志
      let isMatched = false;
      const urlString = typeof url === 'string' ? url : url.toString();
      const method = options.method || 'GET';
      for (const rule of interceptionRules) {
        if (rule.enabled !== false && 
            isUrlMatch(urlString, rule.urlPattern, rule.matchType) && 
            (!rule.method || rule.method === method)) {
          isMatched = true;
          break;
        }
      }
      
      if (isMatched) {
        console.error('❌ [页面拦截] Fetch错误:', error);
      }
      throw error;
    }
  };

  // 拦截 XMLHttpRequest
  const originalOpen = XMLHttpRequest.prototype.open;
  const originalSend = XMLHttpRequest.prototype.send;

  XMLHttpRequest.prototype.open = function(method, url, ...rest) {
    this._method = method;
    this._url = url;
    // 保存请求体数据
    this._requestData = null;
    return originalOpen.apply(this, [method, url, ...rest]);
  };

  XMLHttpRequest.prototype.send = function(...args) {
    const xhr = this;
    // 保存请求体数据
    if (args[0]) {
      this._requestData = args[0];
    }
    
    xhr.addEventListener('load', function() {
      const urlString = xhr._url || '';
      const method = xhr._method || 'GET';
      
      // 特殊处理：捕获请求体中的shopId（仅当规则要求时）
      let shopIds = [];
      let shouldExtractShopId = false;
      let matchedRuleForShopId = null;
      
      // 检查是否有启用extractShopId的规则匹配当前请求
      for (const rule of interceptionRules) {
        if (rule.enabled !== false && rule.extractShopId && 
            isUrlMatch(urlString, rule.urlPattern, rule.matchType) && 
            (!rule.method || rule.method === method)) {
          shouldExtractShopId = true;
          matchedRuleForShopId = rule;
          break;
        }
      }
      
      if (shouldExtractShopId && xhr._requestData && typeof xhr._requestData === 'string') {
        try {
          const requestBody = JSON.parse(xhr._requestData);
          if (requestBody.shopId) {
            shopIds.push(requestBody.shopId.toString()); // 确保是字符串格式
          }
          // 如果有shopIds数组字段
          if (requestBody.shopIds && Array.isArray(requestBody.shopIds)) {
            shopIds = shopIds.concat(requestBody.shopIds.map(id => id.toString())); // 确保是字符串格式
          }
        } catch (e) {
          // 如果不是有效的JSON，忽略错误
        }
      }
      
      // 检查是否匹配拦截规则
      let isMatched = false;
      let matchedRule = null;
      for (const rule of interceptionRules) {
        // 检查规则是否启用，URL和方法是否匹配
        if (rule.enabled !== false && 
            isUrlMatch(urlString, rule.urlPattern, rule.matchType) && 
            (!rule.method || rule.method === method)) {
          isMatched = true;
          matchedRule = rule;
          break;
        }
      }
      
      // 只有匹配到拦截规则时才输出日志和发送数据
      if (isMatched) {
        console.log('🔍 XHR请求:', urlString, 'Method:', method);
        console.log('✅ XHR匹配到规则:', matchedRule.urlPattern, 'Method:', matchedRule.method || 'ALL', 'MatchType:', matchedRule.matchType || 'includes');
        console.log('✅ [页面拦截] XHR匹配到目标URL:', urlString);
        
        let responseData;
        try {
          responseData = JSON.parse(xhr.responseText);
        } catch (e) {
          responseData = xhr.responseText;
        }
      
        console.log('📦 [页面拦截] XHR响应数据:', responseData);

        // 构造发送到content script的数据
        const messageData = {
          url: urlString,
          fullUrl: urlString.startsWith('http') ? urlString : window.location.origin + urlString,
          method: method,
          timestamp: new Date().toISOString(),
          response: responseData, // 发送完整的响应数据
          status: xhr.status,
          captureHtml: matchedRule.captureHtml,  // 添加捕获HTML标志
          shopIds: shopIds.length > 0 ? shopIds : undefined  // 添加shopIds
        };

        // 特殊处理：如果需要提取ShopId并且匹配了目标ShopId，则发送完整数据但标记需要提取ShopId
        if (shouldExtractShopId && shopIds.length > 0 && matchedRuleForShopId) {
          // 确保targetShopIds是数组格式
          const targetShopIdsArray = Array.isArray(matchedRuleForShopId.targetShopIds) ? 
                              matchedRuleForShopId.targetShopIds : 
                              (matchedRuleForShopId.targetShopIds && typeof matchedRuleForShopId.targetShopIds === 'object' ? 
                               Object.values(matchedRuleForShopId.targetShopIds) : 
                               []);
      
          // 检查是否匹配目标ShopId
          let shopIdMatched = false;
          if (!targetShopIdsArray || targetShopIdsArray.length === 0) {
            // 如果没有指定目标ShopId，则匹配所有
            shopIdMatched = true;
          } else {
            // 检查是否有任何一个shopId在目标列表中
            for (const shopId of shopIds) {
              if (targetShopIdsArray.includes(shopId)) {
                shopIdMatched = true;
                break;
              }
            }
          }
          
          if (shopIdMatched) {
            console.log('✅ [页面拦截] ShopId匹配成功:', shopIds.join(', '));
            // 发送完整数据，但标记需要提取ShopId
            messageData.extractShopId = true;
          } else {
            console.log('ℹ️ [页面拦截] ShopId不匹配目标列表:', shopIds.join(', '), '目标列表:', targetShopIdsArray.join(', '));
            // 如果ShopId不匹配，则不发送数据
            return;
          }
        }
        
        // 发送自定义事件到 content script
        window.postMessage({
          type: 'INTERCEPTED_REQUEST',
          data: messageData
        }, '*');
      }
    });

    // 只有匹配到拦截规则时才输出错误日志
    xhr.addEventListener('error', function() {
      const urlString = xhr._url || '';
      const method = xhr._method || 'GET';
      
      let isMatched = false;
      for (const rule of interceptionRules) {
        if (rule.enabled !== false && 
            isUrlMatch(urlString, rule.urlPattern, rule.matchType) && 
            (!rule.method || rule.method === method)) {
          isMatched = true;
          break;
        }
      }
      
      if (isMatched) {
        console.error('❌ [页面拦截] XHR错误:', urlString);
      }
    });
    
    return originalSend.apply(this, args);
  };

  // URL匹配函数
  function isUrlMatch(url, pattern, matchType) {
    // 如果没有指定匹配类型，默认使用includes
    if (!matchType || matchType === 'includes') {
      return url.includes(pattern);
    }
    
    // 精确匹配
    if (matchType === 'exact') {
      // 移除查询参数后进行精确匹配
      const urlWithoutQuery = url.split('?')[0];
      return urlWithoutQuery === pattern;
    }
    
    // 前缀匹配
    if (matchType === 'startsWith') {
      return url.startsWith(pattern);
    }
    
    // 后缀匹配
    if (matchType === 'endsWith') {
      return url.endsWith(pattern);
    }
    
    // 正则表达式匹配
    if (matchType === 'regex') {
      try {
        const regex = new RegExp(pattern);
        return regex.test(url);
      } catch (e) {
        console.error('❌ 正则表达式错误:', pattern, e);
        return false;
      }
    }
    
    // 默认使用includes
    return url.includes(pattern);
  }

  console.log('✅ [页面拦截] 页面上下文拦截器启动完成');
})();